<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="供应商" prop="supplier">
            <el-input
              v-model="queryParams.supplier"
              placeholder="请输入供应商"
              clearable
              @keyup.enter.native="handleQuery"
              style="width:150px"
            />
          </el-form-item>
          <el-form-item label="客户名称" prop="enterpriseName">
            <el-input
              v-model="queryParams.enterpriseName"
              placeholder="请输入客户名称"
              clearable
              @keyup.enter.native="handleQuery"
              style="width:150px"
            />
          </el-form-item>
          <el-form-item label="项目名称" prop="projectName">
            <el-input
              v-model="queryParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
              style="width:150px"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" >
              <el-option
                v-for="dict in dict.type.procure_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select >
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table :row-style="{ height: '25px' }"  :cell-style="{ padding: '0px' }" height="450" border v-loading="loading" :data="purchasingList" @selection-change="handleSelectionChange" highlight-current-row>
          <el-table-column label="序号" type="index" :index="indexMethod"/>
          <el-table-column label="审核状态" align="center" prop="examineStatus" :show-overflow-tooltip="true"/>
          <el-table-column label="合作编号" align="center" prop="purchasingNo" :show-overflow-tooltip="true"/>
          <el-table-column label="建立时间" align="center" prop="establishTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.establishTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="供应商" align="center" prop="supplier" :show-overflow-tooltip="true"/>
          <el-table-column label="客户名称" align="center" prop="enterpriseName" :show-overflow-tooltip="true"/>
          <el-table-column label="项目编号" align="center" prop="projectNo" :show-overflow-tooltip="true"/>
          <el-table-column label="项目名称" align="center" prop="projectName" :show-overflow-tooltip="true"/>
          <el-table-column label="计划时间" align="center" prop="planTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="完成时间" align="center" prop="completeTime" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.completeTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="费用" align="center" prop="fee" />
          <el-table-column label="单价" align="center" prop="unitPrice" />
          <el-table-column label="总价" align="center" prop="totalPrice" />
          <el-table-column label="状态" align="center" prop="status"  >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.procure_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center" prop="fileUpload" >
            <template slot-scope="scope">
              <el-button @click.stop="handlePictureCardPreview(scope.row.fileUpload)" size="small"
                         type="text">附件</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-order"
                v-if="scope.row.examineStatus=='未提交'|| scope.row.examineStatus=='打回'"
                @click="handleUpdate(scope.row,scope.$index)"
                title="提交"
              ></el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-set-up"
                @click="handleClick(scope.row,scope.$index)"
                title="查看"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

      </el-col>
    </el-row>
    <!-- 添加或修改采购管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body @close="cancel">
      <el-tabs v-model="activeName" >
        <el-tab-pane label="合作信息" name="first">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true" >
            <div v-if="addSign!==0">
              <el-descriptions title="">
                <el-descriptions-item label="序号">
                  <el-tag size="medium">{{form.index}}</el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <el-form-item label="合作编号" prop="purchasingNo" :disabled="selectSign">
              <el-input v-model="form.purchasingNo" placeholder="请输入合作编号"    :disabled="true"/>
            </el-form-item>
            <el-form-item label="建立时间" prop="establishTime" :disabled="selectSign">
              <el-date-picker clearable
                              v-model="form.establishTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择建立时间"
                              style="width: 178px"
                              :disabled="true">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="客户名称" prop="enterpriseName" >
              <el-input v-model="form.enterpriseName" placeholder="请输入客户名称" :disabled="selectSign" />
            </el-form-item>
            <el-form-item label="项目编号" prop="projectNo" >
              <el-input v-model="form.projectNo" placeholder="请输入项目编号" :disabled="selectSign"/>
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName" >
              <el-input v-model="form.projectName" placeholder="请输入项目名称" :disabled="selectSign"/>
            </el-form-item>
            <el-form-item label="开户银行" prop="bankName" >
              <el-input v-model="form.bankName" placeholder="请输入开户银行" :disabled="selectSign"/>
            </el-form-item>
            <el-form-item label="开户账号" prop="bankNo" >
              <el-input v-model="form.bankNo" placeholder="请输入开户银行" :disabled="selectSign"/>
            </el-form-item>
            <el-form-item label="费用" prop="fee">
              <el-input v-model="form.fee" placeholder="请输入费用" :disabled="selectSign" style="width: 178px;"/>
            </el-form-item>
            <el-form-item label="计划时间" prop="planTime" >
              <el-date-picker clearable
                              v-model="form.planTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择计划时间"
                              style="width: 178px"
                              :disabled="selectSignOpen">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="完成时间" prop="completeTime">
              <el-date-picker clearable
                              v-model="form.completeTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择完成时间"
                              style="width: 178px"
                              :disabled="selectSignOpen">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="供应商" prop="supplier" >
              <el-input v-model="form.supplier" placeholder="请输入供应商" :disabled="selectSignOpen"  @focus="enterprise"/>
            </el-form-item>
            <el-form-item label="数量" prop="num" >
              <el-input v-model="form.num" placeholder="请输入数量" :disabled="selectSignOpen" type="number" pattern="[0-9]*" :min="0" @focus="updateTotalPrice"/>
            </el-form-item>
            <el-form-item label="单价" prop="unitPrice" >
              <el-input v-model="form.unitPrice" placeholder="请输入单价" :disabled="selectSignOpen" @focus="updateTotalPrice"/>
            </el-form-item>
            <el-form-item label="总价" prop="totalPrice" >
              <el-input v-model="form.totalPrice" placeholder="请输入总价" :disabled="selectSign" />
            </el-form-item>
            <el-form-item label="审核人" prop="examineName" >
              <el-input v-model="form.examineName" placeholder="请输入审核人" @focus="selectOpen(0)" :disabled="selectSignOpen"/>
            </el-form-item>
            <el-form-item label="状态" prop="status" >
              <el-select v-model="form.status" placeholder="请选择状态"  style="width: 178px" :disabled="selectSignOpen">
                <el-option
                  v-for="dict in dict.type.procure_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="附件" prop="fileUpload" style="width: 100%" >
              <file-view  v-if="show"  :limit="1" :type="typeSelect" :businessId="form.fileUpload" :businessCode="businessCode" ></file-view>
            </el-form-item>
          </el-form>
          <div style="align-items: center;justify-content: center;display: flex;">
            <el-button type="primary" @click="submitForm" v-if="addSign!==2">提 交</el-button>
            <el-button @click="cancel">关 闭</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <!--    附件展示对话框-->
    <el-dialog title="查看附件" :visible.sync="openFileList" width="500px" append-to-body v-if="openFileList">
      <UploadFile :upload-id="uploadId" :business-code="businessCode"></UploadFile>
    </el-dialog>
    <select-user ref="select"  :type="userType" :sign="sign" @ok="selectUser"></select-user>
    <!--    选择供应商-->
    <el-dialog :title="title" :visible.sync="openEnter" width="1000px" append-to-body>
      <el-row>
<!--        <el-col :span="5">-->
<!--          <MainType :typeCode="enterpriseCode" @getNode="getNodeEnterprise" :isTree="isTree"></MainType>-->
<!--        </el-col>-->
        <el-col :span="24">
          <el-form :model="queryEnterpriseParams" ref="queryFormEnterprise" size="small" :inline="true"
                   v-show="showSearch" label-width="100px">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="queryEnterpriseParams.enterpriseName" placeholder="请输入企业名称" clearable
                        @keyup.enter.native="handleQueryEnterprise" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini"
                         @click="handleQueryEnterprise">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQueryEnterprise">重置</el-button>
              <el-button type="primary" size="mini" @click="saveSelectEnterprise">确定</el-button>
            </el-form-item>
          </el-form>
          <el-table ref="tableEnterprise" v-loading="loading" style="width: 100%"
                    @selection-change="handleSelectionChangeEnterprise" :data="enterInfoList" highlight-current-row>
            <el-table-column type="selection" width="45" align="center" />
            <el-table-column label="企业名称" align="center" prop="enterpriseName" />
            <el-table-column label="联系人" align="center" prop="contacts" />
            <el-table-column label="联系电话" align="center" prop="telephone" show-overflow-tooltip="true" />
          </el-table>
          <pagination v-show="total1 > 0" :total="total1" :page.sync="queryEnterpriseParams.pageNum"
                      :limit.sync="queryEnterpriseParams.pageSize" @pagination="getEnterpriseList" />
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listCooperate, getPurchasing, updateCooperate, addPurchasing, updatePurchasing,findLastNo } from "@/api/procure/purchasing";
import FileView from "@/components/FileView/index"
import {listType} from "@/api/maintype/type";
import MainType from "../../components/MainType/index.vue";
import Treeselect from "@riophae/vue-treeselect";
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/procure/record";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import UploadFile from "../upload/index.vue";
import SelectUser from "../system/role/selectUser.vue";
import { listInfo } from "@/api/enterprise/info";
export default {
  name: "Purchasing",
  components: {SelectUser, UploadFile, MainType,FileView,Treeselect},
  dicts: ['procure_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      addSign:0,
      dialogImageUrl:null,
      enterInfoList: [],
      total1: 0,
      ImgDig:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      //附件对话框
      openFileList:false,
      uploadId:null,
      //主分类
      options:null,
      isTree: false,
      //查看标志
      selectSign:true,
      enterpriseCode: "enterprise",
      // 非多个禁用
      multiple: true,
      selectSignOpen:false,//默认修改
      //选显卡默认选中
      activeName: 'first',
      typeCode:'purchasing',
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      show:false,
      typeSelect:0,
      businessCode:'procure',
      // 采购管理表格数据
      purchasingList: [],
      // 弹出层标题
      title: "",
      recordList:[],
      //是否为项目管理过来的，从项目管理过来的一些数据是不允许修改
      isShow:false,
      totalRecord:0,
      // 是否显示弹出层
      open: false,
      openEnter:false,
      userType:"1",
      sign:'1',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        supplier: null,
        enterpriseName: null,
        classificationId: null,
        projectName:null,
        status:null,
      },
      queryEnterpriseParams: {
        pageNum: 1,
        pageSize: 15,
        enterpriseName: null,
        classificationId: null
      },
      queryParamsRecord:{
        pageNum: 1,
        pageSize: 15,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        supplier: [
          { required: true, message: '请输入供应商', trigger: 'change' }
        ],
        enterpriseName: [
          { required: true, message: '请输入客户名称', trigger: 'change' }
        ],
        projectNo: [
          { required: true, message: '请输入项目编号', trigger: 'change' },
        ],
        planTime: [
          {  required: true, message: '请选择计划时间', trigger: 'change' }
        ],
        completeTime: [
          {  required: true, message: '请选择完成时间', trigger: 'change' }
        ],
        realityFee: [
          { required: true, message: '请输入实付费用', trigger: 'change' },
        ],
        examineName: [
          { required: true, message: '请输入审核人', trigger: 'blur' }
        ],
        status: [
          {  required: true, message: '请至少选择一种状态', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入数量', trigger: 'blur' },
        ],
        unitPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的单价，最多保留两位小数', trigger: 'blur' }
        ],
        fee: [
          { required: true, message: '请输入费用', trigger: 'change' },
        ],
        projectName: [
          { required: true, message: '请输入项目编号', trigger: 'change' },
        ],
        fileUpload: [
          { required: true, message: '附件不能为空' },
          {
            validator:  (rule, value, callback) => {

              if (!value && this.form.fileUpload) {
                return callback(new Error('附件不能为空'));
              } else {
                callback();
              }
            },
            trigger: 'change',
            required:true
          }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.listType();
  },
  watch: {
    'form.unitPrice': 'updateTotalPrice',
    'form.num': 'updateTotalPrice',
  },
  methods: {
    /** 查询采购管理列表 */
    getList() {
      this.loading = true;
      listCooperate(this.queryParams).then(response => {
        this.purchasingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    updateTotalPrice() {
      if (this.form.unitPrice !== null && this.form.num !== null) {
        // 计算未舍入的总价
        const totalPrice = this.form.unitPrice * this.form.num;
        // 四舍五入为两位小数并转换为数字
        this.form.totalPrice = Number(totalPrice.toFixed(2));
      } else {
        this.form.totalPrice = null;
      }
    },
    getNodeEnterprise(data, node, obj) {
      this.queryEnterpriseParams.classificationId = data.id
      this.getEnterpriseList()
    },
    selectUser(userId, userName) {
      this.$set(this.form, 'examineId', userId)
      this.$set(this.form, 'examineName', userName)
    },
    selectOpen(type){
      this.userType=1;
      this.$refs.select.show();
    },
    getEnterpriseList() {
      this.loading = true;
      listInfo(this.queryEnterpriseParams).then(response => {
        this.enterInfoList = response.rows;
        this.total1 = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
      this.getList();
      this.open = false;
      this.show=false;
      this.typeSelect=0;
    },
    handleQueryEnterprise() {
      this.queryEnterpriseParams.pageNum = 1;
      this.getEnterpriseList();
    },
    /** 重置按钮操作 */
    resetQueryEnterprise() {
      this.resetForm("queryFormEnterprise");
      this.handleQueryEnterprise();
    },
    saveSelectEnterprise() {
      if (this.eIds.toString() == "" || this.eIds.toString() == null) {
        this.$modal.msgError("请先选择客户！");
      } else {
        this.$set(this.form, 'supplier', this.eName.toString())
        this.$set(this.form, 'outsourcingId', this.eIds.toString())
        this.closeOpen()
      }
    },
    closeOpen() {
      this.openEnter = false;
    },
    handleSelectionChangeEnterprise(selection) {
      if (selection.length > 1) {
        this.$refs.tableEnterprise.clearSelection(); // 清空所有选择
        this.$refs.tableEnterprise.toggleRowSelection(selection.pop()); // 设置选择项
      } else {
        this.eIds = selection.map(item => item.enterpriseId)
        this.eName = selection.map(item => item.enterpriseName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      }
    },
    enterprise() {
      this.openEnter = true;
      this.getEnterpriseList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classificationId: null,
        purchasingNo: null,
        establishTime: null,
        supplier: null,
        enterpriseName: null,
        projectNo: null,
        projectName: null,
        planName: null,
        planTime: null,
        completeTime: null,
        fee: null,
        realityFee: null,
        status: null,
        fileUpload: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        creationTime: null,
        operateTime: null,
        isProject: null,
        num:null,
        unitPrice:null,
        bankName:null,
        bankNo:null,
        examineId:null,
        examineName:null,
        isSubmit:null,
        examineStatus:null,
        totalPrice:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //序号展示
    indexMethod(index){
      return (this.queryParams.pageNum-1)*this.queryParams.pageSize +index+1;
    },
    //序号展示
    indexMethodRecord(index){
      return (this.queryParamsRecord.pageNum-1)*this.queryParamsRecord.pageSize +index+1;
    },
    //获取树节点数据
    listType(){
      listType({typeCode:'purchasing'}).then(res=>{
        console.log(this.options)
        this.options=res.data;
      })
    },
    //点击编号查看
    handleClick(row,index){
      this.reset();
      this.selectSign=true;
      this.isShow=true;
      getPurchasing(row.id).then(response => {
        if (response.data.isProject=='1'){
          this.isShow=true;
        }
        this.selectSignOpen=true;
        this.form = response.data;
        this.addSign=2;
        this.typeSelect=2;
        this.form.index=index+1;
        this.open = true;
        this.show=true;
        this.title = "查看合作信息";
        this.getRecordList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row,index) {
      const id = row.id || this.ids
      this.selectSignOpen=false;
      getPurchasing(id).then(response => {
        if (response.data.isProject==='1'){
          this.isShow=true;
        }
        this.form = response.data;
        if (this.form.fileUpload==null){
          this.form.fileUpload=new Date().getTime();
        }
        this.listType();
        this.addSign=1;
        this.typeSelect=1;
        this.form.index=index+1;
        this.open = true;
        this.show=true;
        this.title = "提交合作信息";
        this.getRecordList();
      });
    },
    /** 查询采购管理变更记录列表 */
    getRecordList() {
      this.loading = true;
      listRecord(this.queryParamsRecord).then(response => {
        this.recordList = response.rows;
        this.totalRecord = response.total;
      });
    },
    //树点击事件
    getNode(data){
      console.log(data)
      if(data.parentId!=='00000000-0000-0000-0000-000000000000'){
        this.queryParams.classificationId=data.id
      }else {
        this.queryParams.classificationId=null;
      }
      this.getList()
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCooperate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchasing(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('procure/purchasing/exportCooperate', {
        ...this.queryParams
      }, `purchasing_${new Date().getTime()}.xlsx`)
    },
    handlePictureCardPreview(id) {
      this.uploadId=id;
      this.openFileList = true;
    },
  }
};
</script>
